package com.xky.ui.module.supplierManagement.update;

import com.xky.pojo.Supplier;
import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;

public class UpdateSupplier extends JFrame {
    private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
    private JTextField[] textFields;
    private JComboBox<String> isActiveComboBox;
    private JButton updateButton, queryButton;
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
    
    // 邮箱验证正则表达式
    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";

    public UpdateSupplier() {
        initializeFrame();
        initComponents();
        setVisible(true);
    }

    private void initializeFrame() {
        setTitle("供应商信息修改");
        setSize(600, 680);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initComponents() {
        // 初始化textFields数组
        textFields = new JTextField[8]; // 供应商ID + 7个字段
        for (int i = 0; i < textFields.length; i++) {
            textFields[i] = new JTextField(20);
        }
        
        // 初始化按钮
        updateButton = new JButton("修改");
        queryButton = new JButton("查询");
        
        // 创建主面板并设置背景渐变
        mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 1. 头部面板
        createHeaderPanel();

        // 2. 表单面板
        createFormPanel();

        // 3. 按钮面板
        createButtonPanel();

        // 添加事件监听
        setupEventListeners();

        add(mainPanel);
    }

    private void createHeaderPanel() {
        headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);
        
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel("供应商信息修改");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        hintPanel.setOpaque(false);
        
        JLabel hintLabel = new JLabel("请输入供应商ID查询后再修改");
        hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
        hintLabel.setForeground(Color.GRAY);
        hintPanel.add(hintLabel);
        
        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(PRIMARY_COLOR);
        separator.setPreferredSize(new Dimension(450, 2));
        
        headerPanel.add(titlePanel, BorderLayout.NORTH);
        headerPanel.add(hintPanel, BorderLayout.CENTER);
        headerPanel.add(separator, BorderLayout.SOUTH);
        headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
        
        mainPanel.add(headerPanel, BorderLayout.NORTH);
    }

    private void createFormPanel() {
        // 创建查询面板
        JPanel searchCard = createRoundedPanel();
        searchCard.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 15));
        
        JLabel idLabel = new JLabel("供应商ID");
        idLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        idLabel.setForeground(PRIMARY_COLOR);
        searchCard.add(idLabel);

        textFields[0].setFont(new Font("微软雅黑", Font.PLAIN, 16));
        searchCard.add(textFields[0]);
        
        styleButton(queryButton, QUERY_BUTTON_COLOR);
        queryButton.setPreferredSize(new Dimension(80, 35));
        searchCard.add(queryButton);
        
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setOpaque(false);
        topPanel.add(searchCard, BorderLayout.CENTER);
        topPanel.setBorder(new EmptyBorder(0, 0, 15, 0));
        
        mainPanel.add(topPanel, BorderLayout.NORTH);
        
        // 创建表单面板
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());
        
        formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(10, 10, 10, 10);
        
        String[] labels = {
            "供应商编码 *", "供应商名称 *", "联系人姓名 *", "联系人电话 *", 
            "联系人邮箱 *", "供应商地址 *", "是否合作 *"
        };
        
        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);
        
        for (int i = 0; i < labels.length; i++) {
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.weightx = 0.3;
            
            JLabel label = new JLabel(labels[i]);
            label.setFont(labelFont);
            label.setForeground(PRIMARY_COLOR);
            formPanel.add(label, gbc);
            
            gbc.gridx = 1;
            gbc.weightx = 0.7;
            
            if (i < 6) {
                // 使用已初始化的textFields[i+1]
                textFields[i + 1].setFont(fieldFont);
                textFields[i + 1].setPreferredSize(new Dimension(250, 35));
                formPanel.add(textFields[i + 1], gbc);
            } else {
                isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
                isActiveComboBox.setFont(fieldFont);
                isActiveComboBox.setPreferredSize(new Dimension(250, 35));
                isActiveComboBox.setBackground(Color.WHITE);
                formPanel.add(isActiveComboBox, gbc);
            }
        }

        
        formCard.add(formPanel, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        mainPanel.add(formCard, BorderLayout.CENTER);
        
        // 禁用表单字段，直到用户搜索到供应商
        setFormFieldsEnabled(false);
    }

    private void createButtonPanel() {
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);

        styleButton(updateButton, BUTTON_COLOR);
        updateButton.setEnabled(false);

        buttonPanel.add(updateButton);

        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
    }
    
    private void styleButton(JButton button, Color bgColor) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(120, 40));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
    }
    
    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setOpaque(false);
        
        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
            )
        ));
        
        return panel;
    }
    
    /**
     * 启用或禁用表单字段
     */
    private void setFormFieldsEnabled(boolean enabled) {
        for (int i = 1; i < textFields.length; i++) {
            textFields[i].setEnabled(enabled);
        }
        if (isActiveComboBox != null) {
            isActiveComboBox.setEnabled(enabled);
        }
        updateButton.setEnabled(enabled);
    }

    private void setupEventListeners() {
        // 查询按钮事件
        queryButton.addActionListener(e -> {
            try {
                String idText = textFields[0].getText().trim();
                if (idText.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "请输入供应商ID", "输入错误", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                int supplierId = Integer.parseInt(idText);
                Supplier supplier = findSupplierById(supplierId);
                
                if (supplier != null) {
                    // 填充表单字段
                    textFields[1].setText(supplier.getSupplierCode());
                    textFields[2].setText(supplier.getSupplierName());
                    textFields[3].setText(supplier.getContactName());
                    textFields[4].setText(supplier.getContactPhone());
                    textFields[5].setText(supplier.getContactEmail());
                    textFields[6].setText(supplier.getAddress());
                    
                    // 设置是否合作下拉框
                    isActiveComboBox.setSelectedIndex("1".equals(supplier.getIsActive()) ? 0 : 1);
                    
                    // 启用表单字段
                    setFormFieldsEnabled(true);
                } else {
                    JOptionPane.showMessageDialog(this, "未找到ID为 " + supplierId + " 的供应商记录", 
                            "查找失败", JOptionPane.WARNING_MESSAGE);
                    clearFormFields();
                    setFormFieldsEnabled(false);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        
        // 修改按钮事件
        updateButton.addActionListener(e -> {
            try {
                int supplierId = Integer.parseInt(textFields[0].getText().trim());
                String supplierCode = textFields[1].getText().trim();
                String supplierName = textFields[2].getText().trim();
                String contactName = textFields[3].getText().trim();
                String contactPhone = textFields[4].getText().trim();
                String contactEmail = textFields[5].getText().trim();
                String address = textFields[6].getText().trim();
                String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1，"否"对应0
                
                // 验证输入
                if (!validateInputs(supplierCode, supplierName, contactName, contactPhone, contactEmail, address)) {
                    return;
                }
                
                // 更新供应商信息
                if (updateSupplier(supplierId, supplierCode, supplierName, contactName, contactPhone, contactEmail, address, isActive)) {
                    JOptionPane.showMessageDialog(this, "供应商信息更新成功", "更新成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "供应商信息更新失败", "更新失败", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "供应商ID格式错误", "输入错误", JOptionPane.WARNING_MESSAGE);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        
        // 为ID文本框添加回车键事件
        textFields[0].addActionListener(e -> queryButton.doClick());
    }
    
    private void clearFormFields() {
        for (int i = 1; i < textFields.length; i++) {
            textFields[i].setText("");
        }
        if (isActiveComboBox != null) {
            isActiveComboBox.setSelectedIndex(0);
        }
    }
    
    private boolean validateInputs(String supplierCode, String supplierName, String contactName,
                                  String contactPhone, String contactEmail, String address) {
        // 1. 校验供应商编码
        if (supplierCode.isEmpty()) {
            showValidationError("供应商编码不能为空");
            return false;
        }
        
        // 2. 校验供应商名称
        if (supplierName.isEmpty()) {
            showValidationError("供应商名称不能为空");
            return false;
        }
        
        // 3. 校验联系人姓名
        if (contactName.isEmpty()) {
            showValidationError("联系人姓名不能为空");
            return false;
        }
        
        // 4. 校验联系人电话
        if (contactPhone.isEmpty()) {
            showValidationError("联系人电话不能为空");
            return false;
        }
        
        // 5. 校验联系人邮箱
        if (contactEmail.isEmpty()) {
            showValidationError("联系人邮箱不能为空");
            return false;
        }
        
        // 验证邮箱格式
        if (!contactEmail.matches(EMAIL_REGEX)) {
            showValidationError("邮箱格式不正确");
            return false;
        }
        
        // 6. 校验供应商地址
        if (address.isEmpty()) {
            showValidationError("供应商地址不能为空");
            return false;
        }
        
        return true;
    }
    
    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
    }
    
    private Supplier findSupplierById(int supplierId) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM suppliers WHERE supplier_id = ?");
            preparedStatement.setInt(1, supplierId);
            resultSet = preparedStatement.executeQuery();
            
            if (resultSet.next()) {
                Supplier supplier = new Supplier();
                supplier.setSupplierId(resultSet.getInt("supplier_id"));
                supplier.setSupplierCode(resultSet.getString("supplier_code"));
                supplier.setSupplierName(resultSet.getString("supplier_name"));
                supplier.setContactName(resultSet.getString("contact_name"));
                supplier.setContactPhone(resultSet.getString("contact_phone"));
                supplier.setContactEmail(resultSet.getString("contact_email"));
                supplier.setAddress(resultSet.getString("address"));
                supplier.setIsActive(Boolean.valueOf(resultSet.getString("is_active")));
                return supplier;
            }
            return null;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
    }
    
    private boolean updateSupplier(int supplierId, String supplierCode, String supplierName,
                                  String contactName, String contactPhone, String contactEmail,
                                  String address, String isActive) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement(
                    "UPDATE suppliers SET supplier_code = ?, supplier_name = ?, contact_name = ?, " +
                    "contact_phone = ?, contact_email = ?, address = ?, is_active = ?, updated_time = NOW() " +
                    "WHERE supplier_id = ?");
            preparedStatement.setString(1, supplierCode);
            preparedStatement.setString(2, supplierName);
            preparedStatement.setString(3, contactName);
            preparedStatement.setString(4, contactPhone);
            preparedStatement.setString(5, contactEmail);
            preparedStatement.setString(6, address);
            preparedStatement.setString(7, isActive);
            preparedStatement.setInt(8, supplierId);
            
            return preparedStatement.executeUpdate() > 0;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(UpdateSupplier::new);
    }
}

